<template>
  <div class="dev">
    <!-- 搜索框 -->
    <div class="search">
      <el-input placeholder="请输入版本号" clearable prefix-icon="el-icon-search" v-model="versionNum">
      </el-input>
      <el-select
       style="width: 300px !important;"
        clearable
        v-model="otaFlag"
        placeholder="请选择ota标志是开启or关闭"
      >
        <el-option
          v-for="item in otaList"
          :key="item.label"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      <el-button type="success" icon="el-icon-plus" @click="DialogVisible = true">添加</el-button>
    </div>
    <!-- 表格数据 -->
    <div class="table">
      <el-table :data="tableData" ref="isExpand" v-loading="loading" border height="calc(100%-10rem)"
        highlight-current-row stripe style="width: 100%">
        >
        <template slot="empty">
          <el-empty description="暂无数据"></el-empty>
        </template>
        <el-table-column align="center" prop="versionId" label="版本ID">
        </el-table-column>
        <el-table-column align="center" prop="versionNum" label="版本号">
        </el-table-column>
        <el-table-column align="center" prop="hardwareName" label="硬件类别">
        </el-table-column>
        <el-table-column align="center" prop="description" label="备注">
        </el-table-column>
        <el-table-column align="center" prop="createTime" label="创建时间">
        </el-table-column>

        <!-- 暂时注释ota功能 -->
        <el-table-column
                  width="150"
                  align="center"
                  prop="meterStatus"
                  label="ota"
                >
                  <template slot-scope="scope">
                    <el-switch
                      v-model="scope.row.otaFlag"
                      active-color="#13ce66"
                      inactive-color="#DCDFE6"
                      @change="switchItem(scope.row)"
                   
                    >
                    </el-switch>
                  </template>
                </el-table-column>


        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <!-- <el-button type="text" size="small" >设置升级版本</el-button>
            <el-button type="text" size="small">取消</el-button> -->
            <el-button type="text" size="small" @click="edit(scope.row)">备注</el-button>
            <el-button type="text" size="small" @click="delFn(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination v-show="tableData.length !== 0" background @size-change="handleSizeChange"
        @current-change="handleCurrentChange" :current-page="pageNum" :page-sizes="[10, 30, 50, 100, 150, 200]"
        :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 添加版本 -->
    <div class="add">
      <el-dialog title="添加" @close="close" :visible.sync="DialogVisible" width="600px">
        <el-form :model="addForm" ref="addForm" label-width="100px" class="demo-ruleForm">
          <el-form-item required label="版本号">
            <el-input type="text" placeholder="例如:'A0004S0115'" v-model="addForm.versionNum" clearable>
            </el-input>
          </el-form-item>
          <el-form-item required label="文件">
            <el-upload class="upload-demo" action="" :http-request="upload" :on-preview="handlePreview"
              :on-remove="handleRemove" :on-exceed="handleExceed" :before-upload="beforeUpload" :limit="1" accept=".hex"
              :file-list="fileList">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传hex文件</div>
            </el-upload>
          </el-form-item>

          <el-form-item required label="硬件类别">
            <el-select v-model="addForm.hardwareId" placeholder="请选择">
              <el-option v-for="item in typeList" :value="item.hardwareId" :key="item.hardwareId"
                :label="item.hardwareName">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="备注">
            <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="addForm.description">
            </el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="addFn">确 认</el-button>
        </span>
      </el-dialog>
    </div>
    <!-- 修改备注 -->
    <div class="dialog">
      <el-dialog title="修改备注" :visible.sync="editDialogVisible" width="600px">
        <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="textarea">
        </el-input>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editFn">确 认</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
      
<script>
import {
  getVersionApi,
  addVersionApi,
  getTypeApi,
  delVersionApi,
  editVersionApi,
  postIsForbidApi
} from "../../../../api/system/version";
export default {
  data() {
    return {
      loading: false,
      tableData: [],
      pageNum: 1,
      textarea: "",
      pageSize: 10,
      total: null,
      editDialogVisible: false,
      versionNum: "",
      DialogVisible: false,
      addForm: {
        versionNum: "",
        description: "",
        hardwareId: "",
      },
      versionId: "",
      fileList: [],
      file: {}, //上传的文件,
      typeList: [],
      switchItemLoading1:null,
      // ota  	升级标志选项
      otaList: [
        {
          label: "开启",
          value: true
        },
        {
          label: "关闭",
          value: false
        },
     
      ],
      otaFlag:'', // v-model   ota升级标志开启还是关闭的值
    };
  },
  created() {
    this.pageSize = Number(sessionStorage.getItem("pageSize")) || 10;
    this.pageNum = Number(sessionStorage.getItem("pageNum")) || 1;
    this.getVersion(this.pageNum, this.pageSize);
    this.getType();
  },
  destroyed() {
    sessionStorage.removeItem("pageNum");
    sessionStorage.removeItem("pageSize");
  },
  methods: {

       //设置ota升级
      switchItem(e) {
      console.log("e", e);
      if (e.otaFlag == true) {
        this.$confirm("此操作将开启ota升级!请确认是否开启ota升级?(温馨提示：同一设备类型升级的版本只能开启一个！)", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.switchItemLoading1 = this.$loading({
              lock: true,
              text: `开启...`,
              spinner: "el-icon-loading",
              background: "rgba(0, 0, 0, 0.7)"
            });
            let arr = {
              otaFlag: true
            };
            postIsForbidApi(e.versionId, arr)
              .then(res => {
                if (res.code == 200) {
                  this.switchItemLoading1.close();
                  this.$message.success(`开启成功!`);
                  this.search();
                }
              })
              .catch(err => {
                this.switchItemLoading1.close();
                this.search();
              });
          })
          .catch(() => {
            // this.search();
            e.otaFlag = !e.otaFlag;
          });
      } else {
        this.$confirm("此操作将关闭ota升级!请确认关闭ota升级?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(res => {
            this.switchItemLoading1 = this.$loading({
              lock: true,
              text: `解禁中...`,
              spinner: "el-icon-loading",
              background: "rgba(0, 0, 0, 0.7)"
            });
            let arr = {
              otaFlag: false
            };
            postIsForbidApi(e.versionId, arr)
              .then(res => {
                if (res.code == 200) {
                  this.switchItemLoading1.close();
                  this.$message.success(`关闭成功!`);
                  this.search();
                }
              })
              .catch(err => {
                this.switchItemLoading1.close();
                this.search();
              });
          })
          .catch(err => {
            // this.search();
            e.otaFlag = !e.otaFlag;
          });
      }
    },
    // 关闭弹窗
    close() {
      this.DialogVisible = false;
      this.file = {};
      this.addForm = {
        versionNum: "",
        description: "",
        hardwareId: "",
      };
    },
    // 获取硬件类型
    getType() {
      getTypeApi().then((res) => {
        console.log(res);
        this.typeList = res.data;
      });
    },
    // 上传之前
    beforeUpload(e) {
      //   if (e.name.split(".")[1] !== "hex") {
      //     this.$message.warning("上传失败,请选择hex文件!");
      //   }
      console.log(e);
    },
    // 自定义上传
    upload(param) {
      this.file = param;
    },

    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file);
    },
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$message.warning("当前限制选择 1 个文件");
    },
    // 添加
    addFn() {
      const loading = this.$loading({
        target: document.querySelector(".add .el-dialog"),
        lock: true,
      });
      console.log(this.addForm);
      const formData = new FormData();
      formData.append("file", this.file.file);
      formData.append("versionNum", this.addForm.versionNum);
      formData.append("hardwareId", this.addForm.hardwareId);
      if (this.addForm.description) {
        formData.append("description", this.addForm.description);
      }
      addVersionApi(formData).then((res) => {
        if (res.code == 200) {
          loading.close();
          console.log(res);
          this.DialogVisible = false;
          this.search();
        } else {
          loading.close();
        }
      });
    },
    // 打开修改备注
    edit(e) {
      this.textarea = e.description;
      this.versionId = e.versionId;
      this.editDialogVisible = true;
    },
    // 确认修改备注
    editFn() {
      let arr = {
        description: this.textarea,
      };
      editVersionApi(this.versionId, arr)
        .then((res) => {
          this.editDialogVisible = false;
          this.$message.success("操作成功");
          this.search();
          this.textarea = "";
        })
        .catch((err) => {
          this.$message.error("修改失败");
        });
    },
    // 删除
    delFn(e) {
      this.$confirm(
        "确认删除此版本？此版本删除后，与此版本关联的工单以及相应的升级记录将会被清空!",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          delVersionApi(e.versionId)
            .then((res) => {
              this.$message.success("删除成功");
              this.search();
            })
            .catch((err) => {
              this.$message.error("删除失败！");
            });
        })
        .catch((err) => {
          this.$message.success("已取消删除");
        });
    },
    // 查询
    search() {
      this.pageNum = 1;
      this.getVersion(this.pageNum, this.pageSize, this.versionNum,this.otaFlag);
      this.$refs.isExpand.bodyWrapper.scrollTop = 0;
    },
    // 获取版本列表
    getVersion(pageNum, pageSize, versionNum,otaFlag) {
      this.loading = true;
      getVersionApi(pageNum, pageSize, versionNum,otaFlag).then((res) => {
        console.log(res);
        this.total = res.data.total;
        if (res.data.rows.length == 0) {
          this.pageNum = this.pageNum - 1;
          if (this.pageNum > 0) {
            this.search();
          } else {
            this.tableData = res.data.rows;
            this.loading = false;
          }
        } else {
          this.loading = false;
          this.tableData = res.data.rows;
        }
      });
    },
    // 分页
    handleSizeChange(val) {
      this.pageNum = 1;
      this.getVersion(this.pageNum, val);
      sessionStorage.setItem("pageSize", val);
      this.pageSize = val;
      this.$refs.isExpand.bodyWrapper.scrollTop = 0;
    },
    handleCurrentChange(val) {
      this.getVersion(val, this.pageSize);
      sessionStorage.setItem("pageNum", val);
      this.pageNum = val;
      this.$refs.isExpand.bodyWrapper.scrollTop = 0;
    },
  },
};
</script>
      
<style lang="scss" scoped>
.dev {
  padding-top: 15px;
  padding: 0 15px;
  height: calc(100vh - 100px);

  .search {
    margin-bottom: 15px;

    .el-input {
      width: 200px;
    }

    .el-button {
      margin-left: 15px;
    }
  }

  .table {
    height: 100%;

    .el-table {
      height: 70%;
    }

    .el-pagination {
      text-align: center;
      margin-top: 20px;
    }
  }
}
</style>